package com.yuwubao.hz_International.services.impl

import com.alipay.api.DefaultAlipayClient
import com.alipay.api.domain.AlipayTradeAppPayModel
import com.alipay.api.request.AlipayTradeAppPayRequest
import com.yuwubao.hz_International.entities.repository.ConsumerRepository
import com.yuwubao.hz_International.entities.repository.RechargeConfigRepository
import com.yuwubao.hz_International.services.AliService
import com.yuwubao.hz_International.util.AlipayConfig
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.math.BigDecimal
import java.util.*
import javax.annotation.Resource

@Service
@Transactional
open class AliServiceImpl : AliService {

    @Resource
    private lateinit var userDao: ConsumerRepository
    @Resource lateinit var rechargeConfigRepository: RechargeConfigRepository

    override fun info(userId: Int, money: Double): String? {
        userDao.findOne(userId) ?: throw NullPointerException("无此用户")
        val minMoney = rechargeConfigRepository.findLast().minRechargeMoney
        if(BigDecimal(money)<minMoney) throw RuntimeException("充值低于最低限额")
        val alipayClient = DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.PRIVATE_KEY, AlipayConfig.FORMAT
                , AlipayConfig.CHARSET, AlipayConfig.PUBLIC_KEY, AlipayConfig.SIGNTYPE)
        val payRequest = AlipayTradeAppPayRequest()
        val model = AlipayTradeAppPayModel()
        model.outTradeNo = UUID.randomUUID().toString().replace("-","")
        model.timeoutExpress = "90m"
        model.totalAmount = money.toString()
        model.productCode = "QUICK_MSECURITY_PAY"
        model.subject = "iphone"
        payRequest.bizModel = model
//        payRequest.notifyUrl = "http://www.allblux.xyz/app/index/top_up_callback"
        payRequest.notifyUrl = "http://47.104.170.54:8080/app/index/top_up_callback"
        val res = alipayClient.sdkExecute(payRequest)
        return res.body
    }
}
